import datetime
import time


def copy_properties(src):

    def _copy(dst):
        dst.__name__ = src.__name__
        dst.__doc__ = src.__doc__
        # dst.__qualname__ = src.__qualname__
        return dst
    return _copy


def logger(t, key=lambda name, duration: print("function {} took {}s".format(name, duration))):

    def decorator(func):

        @copy_properties(func)   # 这个等价于@_copy  # 而@_copy又等价于 wrapper = _copy(wrapper)
        def wrapper(*args, **kwargs):
            print("before")
            start = datetime.datetime.now()
            ret = func(*args, **kwargs)
            print("after")
            duration = (datetime.datetime.now() - start).total_seconds()
            if duration > t:
                # print("function {} took {}s".format(func.__name__, duration))
                key(func.__name__, duration)
            return ret
        return wrapper
    return decorator


@logger(3)    # add = decorator(add)
def add(x, y):
    """
    :x int
    :y int
    :return int
    """
    time.sleep(4)
    return x + y


if __name__ == "__main__":
    print(add(1, 2), add.__name__, add.__doc__, add.__qualname__, sep='\n')
